package com.jyr.ohs.controller;

import com.jyr.ohs.common.PageQueryUtils;
import com.jyr.ohs.common.UnifiedJsonReturn;
import com.jyr.ohs.entity.Course;
import com.jyr.ohs.entity.Issue;
import com.jyr.ohs.entity.Student;
import com.jyr.ohs.entity.SubmitWork;
import com.jyr.ohs.service.StudentService;
import com.sun.deploy.net.HttpResponse;
import com.sun.deploy.net.URLEncoder;
import com.sun.mail.imap.protocol.ID;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.List;

/**
 * @author ZhongJing </p>
 * @Description 学生的Controller层 </p>
 * @date 2021/4/14 5:37 下午 </p>
 */
@RestController
@RequestMapping(value = "/student")
public class StudentController {

    @Autowired
    StudentService studentService;

    /**
     * 跳转到学生登陆页面
     */
    @GetMapping(value = "/toLogin")
    public ModelAndView toLogin() {
        ModelAndView mav = new ModelAndView();
        mav.setViewName("student/login");
        return mav;
    }

    /**
     * 跳转到学生主页
     */
    @GetMapping(value = "/main")
    public ModelAndView main(HttpSession session) {
        ModelAndView mav = new ModelAndView();

        // 设置跳转视图
        mav.setViewName("student/main");

        return mav;
    }

    /**
     * 学生登陆
     *
     * @param name     用户名，就是学生的学号
     * @param password 密码
     * @param session  用户保存学生信息到Session域
     * @return 返回统一的JSON格式
     */
    @PostMapping(value = "/login")
    public UnifiedJsonReturn<Student> login(@RequestParam("username") String name,
                                            @RequestParam("password") String password,
                                            HttpSession session) {

        UnifiedJsonReturn<Student> jsonReturn = studentService.login(name, password);
        Student student = jsonReturn.getData();
        session.setAttribute("student", student);
        jsonReturn.setData(null);
        return jsonReturn;

    }

    /**
     * 学生查找自己所有的课程
     *
     * @param id 学生id
     * @return 课程集合
     */
    @GetMapping(value = "/showCourse")
    public List<Course> showCourse(String id) {
        return studentService.showCourse(id);
    }

    /**
     * 跳转到课程列表
     */
    @GetMapping(value = "/toCourseList")
    public ModelAndView toCourseList(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                     @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize,
                                     HttpSession session) {

        ModelAndView mav = new ModelAndView();

        // 从session域中获取学生信息
        Student student = (Student) session.getAttribute("student");

        // 查询该学生的所有课程
        List<Course> courses = studentService.showCourse(student.getId());

        // 分页
        PageQueryUtils<Course> pageQueryUtils = new PageQueryUtils<>(pageNum, pageSize, courses);
        pageQueryUtils.page();

        // 将分页信息放到request域
        mav.addObject("pageQueryUtils", pageQueryUtils);

        // 设置跳转视图
        mav.setViewName("student/course_list");

        return mav;
    }

    /**
     * 跳转到作业列表页面
     */
    @GetMapping(value = "/toHomeworkList")
    public ModelAndView toHomeworkList(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                       @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize,
                                       Integer cid) {

        ModelAndView mav = new ModelAndView();

        // 查询该课程的所有作业
        List<Issue> issueList = studentService.listIssueByCid(cid);

        // 分页
        PageQueryUtils<Issue> pageQueryUtils = new PageQueryUtils<>(pageNum, pageSize, issueList);
        pageQueryUtils.page();

        // 把分页数据放到request域
        mav.addObject("pageQueryUtils", pageQueryUtils);

        mav.addObject("cid", cid);

        mav.setViewName("student/homework_list");

        return mav;
    }

    /**
     * 下载作业
     */
    @PostMapping(value = "/downloadHomework")
    public void downloadHomework(String filePath, HttpServletResponse response) throws IOException {
        InputStream inputStream = null;
        OutputStream os = null;
        try {
            File file = new File(filePath);
            String name = file.getName();
            inputStream = new FileInputStream(file);
            ByteArrayOutputStream outStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = inputStream.read(buffer)) != -1) {
                outStream.write(buffer, 0, len);
            }
            inputStream.close();
            byte[] data = outStream.toByteArray();
            response.reset();
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(name, "UTF-8"));
            response.setContentType("application/octet-stream");
            os = response.getOutputStream();
            os.write(data);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("下载作业失败");
        } finally {
            if (inputStream != null) {
                inputStream.close();
            }
            if (os != null) {
                os.close();
            }
        }
    }

    /**
     * 跳转到作业提交页面
     */
    @GetMapping(value = "/toSubmitHomework")
    public ModelAndView toSubmitHomework(Integer id, HttpSession session) {
        ModelAndView mav = new ModelAndView();

        // 根据id查询issue信息
        Issue issue = studentService.getIssueById(id);

        // 将数据放到request域
        mav.addObject("issue", issue);

        mav.setViewName("student/submit_homework");

        return mav;
    }

    /**
     * 提交作业
     */
    @PostMapping(value = "/submitHomework")
    public ModelAndView submitHomework(MultipartFile file, SubmitWork submitWork) {
        ModelAndView mav = new ModelAndView();

        boolean flag = studentService.submitHomework(submitWork, file);

        mav.setViewName("redirect:/student/toCourseList");

        return mav;
    }

    @GetMapping(value = "/shutdown")
    public ModelAndView exit(HttpSession session) {
        ModelAndView mav = new ModelAndView();

        session.removeAttribute("student");

        mav.setViewName("common/all_login");

        return mav;
    }

}
